<?php
namespace App\Http\Service;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use App\Http\Service\UserService;
use App\Http\Service\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use App\Models\Doubanpostproduct;
use App\Http\Service\MoneyService;


class SearchService extends BaseService
{
    protected $client;
    protected $baseUrl = 'https://eco.taobao.com/router/rest';

    public function __construct(UserService $userService,Doubanpostproduct $Doubanpostproduct,MoneyService $moneyService)
    {
        $this->userService=$userService;
        $this->getInfo=config('myurl.getInfo');
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->doubanpostproduct=$Doubanpostproduct;
        $this->moneyService=$moneyService;
    }

    public  function getList($request,$data=[])
    {
       // dd($data['limit']);
        $page = !empty($data['page']) && intval($data['page']) ?$data['page'] :$this->cpage;
        $limit = !empty($data['limit']) && intval($data['limit']) ?$data['limit'] :$this->climit;
        //dd($data['limit']);
        $offset = ($page-1)*$limit;


        //用户列表
        $userlist=$this->userService->getList($request);
        $userlist=$userlist['data'];
        //组装数据
        $userdata=[];
        $nicknamedata=[];
        foreach ($userlist as $k => $v) {
            $userdata[$v['id']]=$v['avatar'];
            $nicknamedata[$v['id']]=$v['avatar'];
        }


        $type=$data['type']; //1 爆料  2. 逛逛  0 全部

        //dd($data['content']);
        $list_baoliao=[];
        if($type=='1' || $type=='0' ){

            $where=" where 1=1";
            $where.=" and type in ('2','3','4','5' ) ";


         /*   if($data['content']){
                $keycontent=$data['content'];
                $keycontent = trim($keycontent, "'"); // 移除引号，因为like需要自己加%
                $where.="  and 
                 CONCAT(
                COALESCE(title, ''),
                COALESCE(content, ''),
                COALESCE(y_content, ''),
                COALESCE(category_name, '')

                ) 
                  like '%{$keycontent}%'";
                //die($where);
            }*/
            if($data['content']){
                $keycontent = $data['content'];
                // 转义特殊字符
                // 转义特殊字符：反斜杠、百分号、下划线、单引号
                $keycontent = str_replace(['\\', '%', '_', "'"], ['\\\\', '\%', '\_', "''"], $keycontent);
                $keycontent = '%' . $keycontent . '%';
                
                $where .= " AND CONCAT(
                    COALESCE(title, ''),
                    COALESCE(content, ''),
                    COALESCE(y_content, ''),
                    COALESCE(category_name, '')
                ) LIKE '{$keycontent}'";
            }


            /*if($data['platform_name']){
                $platform_name=$data['platform_name'];
                $platform_list = implode("','", $platform_name);
                $platform_list = "('" . $platform_list . "')";
                $where.="  and   platform_name  in  {$platform_list}";
            }*/
            if($data['platform_name']){
                $platform_name = $data['platform_name'];
                $like_conditions = [];
                
                foreach($platform_name as $platform) {
                    $safe_platform = addslashes(trim($platform));
                    $like_conditions[] = "platform_name LIKE '%{$safe_platform}%'";
                }
                
                $where .= " AND (" . implode(' OR ', $like_conditions) . ")";
            }

            if($data['brand_name']){
                $brand_name=$data['brand_name'];
                $brand_name_list = implode("','", $brand_name);
                $brand_name_list = "('" . $brand_name_list . "')";
                $where.="  and   brand_name  in  {$brand_name_list}";
            }

            $sql="SELECT `id`,`purchase_steps`,`type`,`unique_id`,`platform_name`,`title`,`cover`,`unit_price`,`quantity`,`final_price`,`view_count`,`comment_count`,`collect_count`,`sales_count`,`commission_amount`,`publish_time`,`is_owner`,`subsidy_rate`,`commission_rate`,`user_id` FROM `module_baoliao_post` {$where}  ORDER BY update_time DESC  limit 10 ";
            //die($sql);
            $list_baoliao=DB::select($sql);
            $list_baoliao = array_map('get_object_vars', $list_baoliao);

          
            foreach ($list_baoliao as &$value) {
                $value['unique_type_hduan']='baoliao';
                $value['unique_type_qduan']='baoliao';
                $value['unique_id']="baoliao_{$value['unique_id']}";
                $final_price=$value['final_price'];
                if(empty($final_price)){
                    $final_price=0;
                    $value['final_price']=$final_price;
                }
                $unit_price=$value['unit_price'];
                if(empty($unit_price)){
                    $unit_price=0;
                    $value['unit_price']=$unit_price;
                }
                $view_count=$value['view_count'];
                if(empty($view_count)){
                    $view_count=0;
                    $value['view_count']=$view_count;
                }
                $comment_count=$value['comment_count'];
                if(empty($comment_count)){
                    $comment_count=0;
                    $value['comment_count']=$comment_count;
                }
                $collect_count=$value['collect_count'];
                if(empty($collect_count)){
                    $collect_count=0;
                    $value['collect_count']=$collect_count;
                }
                $sales_count=$value['sales_count'];
                if(empty($sales_count)){
                    $sales_count=0;
                    $value['sales_count']=$sales_count;
                }
                $value['base_score'] = ContentScoringService::calculateReportScore(
                    $final_price,
                    $unit_price,
                    $view_count,
                    $comment_count,
                    $collect_count,
                    $sales_count
                );
                $timestamp = strtotime($value['publish_time']); 
                $value['publish_time']=date('Y-m-d H:i:s',$timestamp);
                $value['days_passed'] = (time() - $timestamp) / 86400; // 计算天数
            }

        }
        $list_douban=[];
        if($type=='2' || $type=='0'){
            $where=" where 1=1";
            $where.=" and status='1' ";
  
            $where.=" and cover !='' ";
            $where.=" and channel='app' ";
            //是否删除 1 删除 2 不删除
            $where.=" and is_delete='2' ";
           
            if(isset($data['title'])&&!empty($data['title'])){
                $where.=" and title like '%{$data['title']}%' ";
            }
            if(isset($data['group_type'])&&!empty($data['group_type'])){
                $where.=" and group_type = '{$data['group_type']}' ";
            }

            if(isset($data['is_official'])&&!empty($data['is_official'])){
                $where.=" and is_official = '{$data['is_official']}' ";
            }

            if($data['content']){
                $content=$data['content'];
                $content = trim($content, "'"); // 移除引号，因为like需要自己加%
                $where.="  and  CONCAT(
                COALESCE(title, ''), 
                COALESCE(content_books, ''), 
                COALESCE(y_content, '')
                )  like '%{$content}%'";
            }

            if($data['platform_name']){
                $where1="";
                $where1.=" where 1=1 ";
                $platform_names=$data['platform_name'];
                $productList=$this->doubanpostproduct->whereIn('platform_name',$platform_names)->select(['post_unique_id'])->get()->toArray();
                $doubanpostproduct=array_column($productList,'post_unique_id');
                $doubanpostproduct = implode("','", $doubanpostproduct);
                $doubanpostproduct_list = "('" . $doubanpostproduct . "')";
                $where.="  and   unique_id  in  {$doubanpostproduct_list}";
                
            }

            if($data['brand_name']){
                $where1="";
                $where1.=" where 1=1 ";
                $brand_name=$data['brand_name'];
                $productList=$this->doubanpostproduct->whereIn('brand_name',$brand_name)->select(['post_unique_id'])->get()->toArray();
                $doubanpostproduct=array_column($productList,'post_unique_id');
                $doubanpostproduct = implode("','", $doubanpostproduct);
                $doubanpostproduct_list = "('" . $doubanpostproduct . "')";
                $where.="  and   unique_id  in  {$doubanpostproduct_list}";
                
            }


            
            $sql="SELECT `id`,`channel`,`user_id`,`avatar`,`is_official`,`nickname`,`unique_id`,`title`,`cover`,`view_count`,`comment_count`,`collect_count`,`sales_count`,`publish_time`,`update_time` FROM `module_douban_post` {$where}  ORDER BY update_time DESC    limit 500 ";
            //die($sql);

            $list_douban=DB::select($sql);
            $list_douban = array_map('get_object_vars', $list_douban);

            foreach ($list_douban as &$value) {
                $value['unique_type_hduan']='douban';
                $value['unique_type_qduan']='guangguang';
                $value['unique_id']="douban_{$value['unique_id']}";
                //$value['avatar_img']=$value['avatar'];
                $user_id=(int)trim($value['user_id']);
                if(isset($userdata[$user_id])){
                    $value['avatar_img'] =$userdata[$user_id];
                }else{
                    $value['avatar_img'] ='http://xingfanapp.oss-cn-hangzhou.aliyuncs.com/uploads/modules/2025-06-11/f6dcc8ae-375a-4957-a59c-6aeb6b191b18.jpg';
                }
                if($value['channel']=='app'){
                    $value['avatar_img'] =$value['avatar'];
                }
                //dd($user_id);
                
                $value['save_time'] =uc_time_ago($value['update_time']);

                $view_count=$value['view_count'];
                if(empty($view_count)){
                    $view_count=0;
                    $value['view_count']=$view_count;
                }
                $comment_count=$value['comment_count'];
                if(empty($comment_count)){
                    $comment_count=0;
                    $value['comment_count']=$comment_count;
                }
                $collect_count=$value['collect_count'];
                if(empty($collect_count)){
                    $collect_count=0;
                    $value['collect_count']=$collect_count;
                }
                $sales_count=$value['sales_count'];
                if(empty($sales_count)){
                    $sales_count=0;
                    $value['sales_count']=$sales_count;
                }
                $value['base_score'] = ContentScoringService::calculatePopularityScore(
                    $view_count,
                    $comment_count,
                    $collect_count,
                    $sales_count
                );
                //dd($value['base_score']);
                $timestamp = strtotime($value['publish_time']); 
                $value['publish_time']=date('m-d H:i',$timestamp);
                $value['days_passed'] = (time() - $timestamp) / 86400; // 计算天数
            }
        }

        $list=array_merge($list_baoliao,$list_douban);


        // dd(count($list));

        $unit_type=$data['unit_type'];

        switch ($unit_type) {
            case "1":
                //综合（按最终得分排序）
                $sortedBy = ContentScoringService::sortContents($list, 'comprehensive');
                break;
            case "2":
                // 最新（按发布时间降序）
                $sortedBy = ContentScoringService::sortContents($list, 'latest');
                break;
            case "3":
                // 最热（按浏览量降序）
                $sortedBy = ContentScoringService::sortContents($list, 'hottest');               
                break; 
             case "4":
                // 高佣金（按佣金降序）
                $sortedBy = ContentScoringService::sortContents($list, 'high_commission');           
                break; 
             case "5":
                // 高销量（按销量降序）
                $sortedBy = ContentScoringService::sortContents($list, 'high_sales');             
                break;
            default:
                //die($sql);
                $sortedBy =$list;
        }
        $people_id=$data['people_id'];
        if(empty($people_id)){
            $people_id=206292;
        }
        //dd($people_id);
        #测试
        $list= array_slice($sortedBy, $offset, $limit);
        if($list){
            foreach($list as $k=>&$val){
                if($val['unique_type_hduan']=='baoliao'){

                    $unit_price=$val['unit_price'];
                    if(empty($val['unit_price'])){
                        $unit_price=0.00;
                    }

                    $subsidy_rate=$val['subsidy_rate'];
                    if(empty($val['subsidy_rate'])){
                        $subsidy_rate=0.00;
                    }
                    $commission_rate=$val['commission_rate'];
                    if(empty($val['commission_rate'])){
                        $commission_rate=0.00;
                    }
                    $is_owner=$val['is_owner'];
                    if(empty($is_owner)){
                        $is_owner=1;

                    }


                    $subsidy_rate=$subsidy_rate/100;
                    $commission_rate=$commission_rate/100;
                    //dd($commission_rate);
                    
                    //平台标识
                    $platform_name=$val['platform_name'];

                    #预估返
                    $estimatedTotalCommission=$this->moneyService->estimatedTotalCommission($unit_price,$subsidy_rate,$commission_rate,$platform_name,$people_id,$is_rate_true=0,$is_owner);
                    //dd($estimatedTotalCommission);
                    $val['commission_amount']=$estimatedTotalCommission['total_commission'];
                    #保留两位小数
                    $val['commission_amount']=_round($val['commission_amount']);
                }

            }
        }

       // dd($list);

        $count = count($sortedBy);

        $result = [
            'page'=> $page,
            'limit'=> $limit,
            'total_page'=> ceil($count/$limit),
            'count'=>$count,
            'data'=> $list
        ];
        return $result; 
    

    }

    //详情
    public  function dataDetail($request,$data=[])
    {
        $unique_id=$data['unique_id'];
        $array = explode('_', $unique_id);
        $type=$array['0'];
        $replaced = str_replace("{$type}_", "", $unique_id);
        //dd($type);
        switch ($type) {
            case "douban":
                //豆瓣
               $sql="SELECT * FROM `module_douban_post` where unique_id='{$replaced}'";
                break;
            case "baoliao":
                // 爆料
                $sql="SELECT * FROM `module_baoliao_post` where unique_id='{$replaced}'";
                break;
            default:
                //die($sql);
                $sql ='';
        }
        //die($sql);
        $list=DB::select($sql);
        $list = array_map('get_object_vars', $list);
        $people_id=$data['people_id'];
        if(empty($people_id)){
            $people_id=206292;
        }
        if(!empty($list) && $type=='douban'){
            $list =$list[0];
            $channel=$list['channel'];
            $guanlian_shop=$list['guanlian_shop'];
            if($channel=='app'){
                //$url=$this->URL_MAP[$platform];
                $url=$this->getInfo;
                $user_id=$list['user_id'];
                $list['guanlian_shop']=$guanlian_shop=json_decode($list['guanlian_shop'],true);
                $guajlian_ar=[];
                //dd($guanlian_shop);
                if($guanlian_shop){


                    foreach($guanlian_shop as $k=>$v){
                        $platformName=$v['platformName'];
                        $productId=$v['productId'];
                        $url=$this->getInfo;
                        $data2=[
                            'platform'=>$platformName,
                            'product_id'=>$productId,
                            'user_id'=>$user_id,
                        ];

                        $postdata=json_post($url,$data2);
                        if($postdata['status']=='200'){
                            $data3=$postdata['data'];
                            $v['data']=$data3;
                            $guajlian_ar[]=$v;

                        }
                        
                    }
                    $list['guanlian_shop']=$guajlian_ar;

                }
            }
            $list['content_books'] =json_decode($list['content_books'],true);       
            $list['images'] =json_decode($list['images'],true);
        }
        if(!empty($list) && $type=='baoliao'){
            $list =$list[0];
            $list['purchase_screenshots'] =json_decode($list['purchase_screenshots'],true);
            $unit_price=$list['unit_price'];
            if(empty($list['unit_price'])){
                $unit_price=0.00;
            }
            $subsidy_rate=$list['subsidy_rate'];
            if(empty($list['subsidy_rate'])){
                $subsidy_rate=0.00;
            }
            $commission_rate=$list['commission_rate'];
            if(empty($list['commission_rate'])){
                $commission_rate=0.00;
            }
            $is_owner=$list['is_owner'];
            if(empty($is_owner)){
                $is_owner=1;

            }


            $subsidy_rate=$list['subsidy_rate']/100;
            $commission_rate=$list['commission_rate']/100;
            //dd($commission_rate);
            
            //平台标识
            $platform_name=$list['platform_name'];
            $quantity=$list['quantity'];
            if(empty($quantity)){
                $quantity=1;
            }

            $title=$list['title'];
        
            #预估返
            $estimated_amount=$this->moneyService->estimated_amount($unit_price,$commission_rate,$platform_name,$people_id,$is_rate_true=0,$is_owner);
            //dd($estimated_amount);
            $list['commission_amount']=$estimated_amount;
            #保留两位小数
            $list['commission_amount']=_round($list['commission_amount']);

            $list['purchase_steps'] =json_decode($list['purchase_steps'],true);

            #重写购买步骤
            $list['purchase_steps'] =$this->moneyService->purchase_steps($list['purchase_steps'],$quantity,$title,$platform_name,$estimated_amount,$unit_price);


            
        }

        return $list;


    }
}
